//
//  searchNewFriendVC.m
//  HappyStore
//
//  Created by 陈锋 on 16/7/29.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "searchNewFriendVC.h"
#import "searchContactsCell.h"
#import "thirdPersonVC.h"

@interface searchNewFriendVC (){
    NSInteger page;

}


// 数据源
@property (strong, nonatomic) NSDictionary * dataDict;
@property (strong, nonatomic) NSMutableArray * dataArr;
@end

static NSString * searchContactscell = @"searchContactsCell";
@implementation searchNewFriendVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self showRoundProgressWithTitle:@"请稍后..."];
    
    // 注册
    UINib * nib = [UINib nibWithNibName:@"searchContactsCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:searchContactscell];
    
    page = 1;
    
    self.title = @"搜索人脉结果";
    
    //设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"Back" highImage:@"Back"];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    // 设置刷新图片
    // 设置刷新图片
    UIImage *images = [UIImage imageNamed:@"mj_footer"];
    NSArray *refreshingImages = @[images];
    [footer setImages:refreshingImages forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多内容了" forState:MJRefreshStateRefreshing];
    footer.stateLabel.font = [UIFont systemFontOfSize:12.0f];
    footer.stateLabel.textColor = [UIColor colorWithWhite:0.6 alpha:1.0f];
    
    [footer setAutomaticallyRefresh:NO];
    
    self.tableView.mj_footer = footer;
    
    [self sendRequest];
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}

-(void)loadMoreData{
    page++;
    [self sendRequest];
    
}

-(void)leftBarButtonItemClick{
    
    self.mhName = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    [tableView tableViewDisplayWitMsg:@"没有查询到相对应的数据" ifNecessaryForRowCount:_dataArr.count];
    return _dataArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    searchContactsCell *cell = [tableView dequeueReusableCellWithIdentifier:searchContactscell forIndexPath:indexPath];
    
    NSDictionary * dict = self.dataArr[indexPath.row];
    
    cell.lineview.hidden = YES;
    
    [cell.headImg sd_setImageWithURL:[NSURL URLWithString:dict[@"headPhoto"]]];
    [cell.headImg.layer setCornerRadius:(cell.headImg.frame.size.height/2)];
    [cell.headImg.layer setMasksToBounds:YES];
    [cell.headImg setContentMode:UIViewContentModeScaleAspectFill];
    [cell.headImg setClipsToBounds:YES];
    cell.headImg.layer.shadowColor = [UIColor whiteColor].CGColor;
    cell.headImg.layer.shadowOffset = CGSizeMake(4, 4);
    cell.headImg.layer.shadowOpacity = 0.5;
    cell.headImg.layer.shadowRadius = 2.0;
    
    if ([dict[@"userName"] isEqualToString:@""] || [dict[@"userName"] isEqualToString:@"null"]) {
        cell.nameLabel.text = dict[@"account"];
    }else{
        cell.nameLabel.text = dict[@"userName"];
    }
    
    
    CGSize size = [cell.nameLabel sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
    
    if (size.width<190) {
        [cell.nameLabel setFrame:CGRectMake(cell.nameLabel.x, cell.nameLabel.y, size.width, cell.nameLabel.height)];
    }else{
        [cell.nameLabel setFrame:CGRectMake(cell.nameLabel.x, cell.nameLabel.y, 168, cell.nameLabel.height)];
    }
    
    cell.lineView.x = cell.nameLabel.x + cell.nameLabel.width + 2;
    
    
    if ([dict[@"positionName"] isEqualToString:@""] || [dict[@"positionName"] isEqualToString:@"null"]) {
        cell.posName.text = @"";
    }else{
        cell.posName.text = dict[@"positionName"];
    }
    CGSize posSize = [cell.posName sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
    if (posSize.width <= 60) {
        cell.posName.width = posSize.width;
    }else{
        cell.posName.width = 60;
    }
    
    cell.posName.x = cell.lineView.x;
    cell.vImg.x = cell.posName.x + cell.posName.width + 2;
    
    if (cell.vImg.x > 185) {
        cell.vImg.x = 184;
    }
    
    cell.lineview.hidden = YES;
    //上级
    cell.detailLabel.text = [UsedTool userType:dict[@"userType"] companyName:dict[@"companyName"] userAddress:dict[@"userAddress"]];
    //会员图标
    cell.vImg.image = [UsedTool setVipimage:dict[@"vipLevel"]];
//    if ([dict[@"authState"]integerValue] == 0) {
//        cell.vImg.image = [UIImage imageNamed:@"weirenzheng"];
//    }else{
//        cell.vImg.image = [UIImage imageNamed:@"yirenzheng"];
//    }
    //认证
    cell.isAuthState.hidden = [UsedTool authStateImageViewHidden:dict[@"authState"]];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 80;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return  1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 30;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.width, 30)];
    view.backgroundColor = [UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1];
    UIImageView * img = [[UIImageView alloc]initWithFrame:CGRectMake(5, 10, 60, 15)];
    img.image = [UIImage imageNamed:@"推荐人脉"];
    [view addSubview:img];
    
    return view;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//取消选中状态
    if (allConstMemberid) {
        NSDictionary * dict = _dataArr[indexPath.row];
        
        NSString * str = [USER_DEFAULTS objectForKey:@"userid"];
        NSInteger userid = [str integerValue];
        
        NSString * str1 = dict[@"userId"];
        NSInteger userId = [str1 integerValue];
        
        if (userid != userId) {
            
            if ([dict[@"type"] isEqualToString:@"政府"]) {
                goveDetailVC * prVC = [[goveDetailVC alloc]init];
                prVC.userType = dict[@"userType"];
                prVC.userId = dict[@"userId"];
                [self.navigationController pushViewController:prVC animated:YES];
                
            }else{
                
                thirdPersonVC * prVC = [[thirdPersonVC alloc]init];
                prVC.userType = dict[@"userType"];
                prVC.userId = dict[@"userId"];
                [self.navigationController pushViewController:prVC animated:YES];
            }
            
        }else{
            
            NSLog(@"点击了自己");
            
        }
        
        
    }else{
        
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
        [alert show];
        
    }
    
    
}

-(void)sendRequest{
    
    // 请求数据
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
    
        
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"userId"];
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
        [muDicParameters setObject:@(page) forKey:@"page"];
        [muDicParameters setObject:self.mhName forKey:@"mhName"];
  
    NSString *str = @"PeopleTuijian_app_people.im";
    
    [LSHttpTool sendHttpData:str params:muDicParameters success:^(id responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        self.dataDict = dicInfo[@"data"];
        
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            if (page == 1) {
                
                _dataArr = nil;
                _dataArr = self.dataDict[@"record"];
                
                
            }else{
                
                NSArray *arr = self.dataDict[@"record"];
                NSMutableArray * mtArr = [NSMutableArray array];
                for (NSDictionary * dict in _dataArr) {
                    [mtArr addObject:dict];
                }
                for (NSDictionary * dict in arr) {
                    [mtArr addObject:dict];
                }
                _dataArr = nil;
                _dataArr = mtArr;
                
            }
            
            [self.tableView.mj_footer endRefreshing];
            
        }else{
            
            [self.tableView.mj_footer endRefreshing];
        }
        
        [self.tableView reloadData];

        [self hideBubble];
        
    } failure:^(NSError *error) {

       [self showSingleIconBubble:@"网络连接错误"];
        
    }];

    
}

#pragma mark - alertview
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        //登录
        UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
        [self presentViewController:loginNAV animated:YES completion:nil];
    }
    
    
}
@end
